<template>
  <div class="organization-onboarding">
    <div class="onboarding-container">
      <div class="onboarding-header">
        <h1>欢迎使用灵犀管理系统</h1>
        <p>让我们帮助您快速设置和管理您的组织</p>
      </div>

      <el-steps :active="currentStep" finish-status="success" simple>
        <el-step title="创建组织" />
        <el-step title="添加成员" />
        <el-step title="设置权限" />
        <el-step title="完成配置" />
      </el-steps>

      <div class="step-content">
        <!-- 步骤1: 创建组织 -->
        <div v-if="currentStep === 0" class="step-panel">
          <el-card class="step-card">
            <template #header>
              <div class="card-header">
                <el-icon><OfficeBuilding /></el-icon>
                <span>创建您的第一个组织</span>
              </div>
            </template>
            
            <el-form 
              :model="organizationForm" 
              :rules="organizationRules" 
              ref="organizationFormRef"
              label-width="100px"
            >
              <el-form-item label="组织名称" prop="name">
                <el-input 
                  v-model="organizationForm.name" 
                  placeholder="请输入组织名称"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
              
              <el-form-item label="组织编码" prop="code">
                <el-input 
                  v-model="organizationForm.code" 
                  placeholder="请输入组织编码"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
              
              <el-form-item label="联系地址" prop="address">
                <el-input 
                  v-model="organizationForm.address" 
                  placeholder="请输入联系地址"
                  type="textarea"
                  :rows="3"
                />
              </el-form-item>
              
              <el-form-item label="联系方式" prop="contactInfo">
                <el-input 
                  v-model="organizationForm.contactInfo" 
                  placeholder="请输入联系方式"
                />
              </el-form-item>
              
              <el-form-item label="描述" prop="description">
                <el-input 
                  v-model="organizationForm.description" 
                  placeholder="请输入组织描述"
                  type="textarea"
                  :rows="3"
                />
              </el-form-item>
            </el-form>
            
            <div class="step-actions">
              <el-button type="primary" @click="createOrganization" :loading="creatingOrganization">
                创建组织
              </el-button>
              <el-button @click="skipOnboarding">跳过向导</el-button>
            </div>
          </el-card>
        </div>

        <!-- 步骤2: 添加成员 -->
        <div v-else-if="currentStep === 1" class="step-panel">
          <el-card class="step-card">
            <template #header>
              <div class="card-header">
                <el-icon><User /></el-icon>
                <span>添加组织成员</span>
              </div>
            </template>
            
            <div class="member-invite">
              <el-alert
                title="提示"
                description="您可以通过邀请链接或直接添加用户来为组织添加成员"
                type="info"
                show-icon
                style="margin-bottom: 20px;"
              />
              
              <!-- 邀请链接 -->
              <el-card class="invite-card" shadow="never">
                <div class="invite-header">
                  <h3>通过邀请链接</h3>
                  <el-button type="primary" size="small" @click="generateInviteLink">
                    生成邀请链接
                  </el-button>
                </div>
                
                <div v-if="inviteLink" class="invite-link-container">
                  <el-input 
                    v-model="inviteLink" 
                    readonly 
                    style="margin-bottom: 10px;"
                  />
                  <el-button @click="copyInviteLink">复制链接</el-button>
                </div>
              </el-card>
              
              <!-- 直接添加用户 -->
              <el-card class="invite-card" shadow="never" style="margin-top: 20px;">
                <div class="invite-header">
                  <h3>直接添加用户</h3>
                </div>
                
                <el-form 
                  :model="userForm" 
                  :rules="userRules" 
                  ref="userFormRef"
                  label-width="80px"
                >
                  <el-form-item label="用户名" prop="name">
                    <el-input 
                      v-model="userForm.name" 
                      placeholder="请输入用户名"
                    />
                  </el-form-item>
                  
                  <el-form-item label="邮箱" prop="email">
                    <el-input 
                      v-model="userForm.email" 
                      placeholder="请输入邮箱"
                      type="email"
                    />
                  </el-form-item>
                  
                  <el-form-item label="角色" prop="role">
                    <el-select v-model="userForm.role" placeholder="请选择角色">
                      <el-option label="管理员" value="admin" />
                      <el-option label="普通用户" value="user" />
                      <el-option label="财务" value="finance" />
                      <el-option label="采购" value="purchase" />
                    </el-select>
                  </el-form-item>
                </el-form>
                
                <div class="form-actions">
                  <el-button @click="addUser" :loading="addingUser">
                    添加用户
                  </el-button>
                </div>
              </el-card>
            </div>
            
            <div class="step-actions">
              <el-button @click="prevStep">上一步</el-button>
              <el-button type="primary" @click="nextStep">下一步</el-button>
            </div>
          </el-card>
        </div>

        <!-- 步骤3: 设置权限 -->
        <div v-else-if="currentStep === 2" class="step-panel">
          <el-card class="step-card">
            <template #header>
              <div class="card-header">
                <el-icon><Lock /></el-icon>
                <span>设置组织权限</span>
              </div>
            </template>
            
            <div class="permission-setup">
              <el-alert
                title="权限说明"
                description="您可以为不同的角色设置不同的权限，确保数据安全"
                type="info"
                show-icon
                style="margin-bottom: 20px;"
              />
              
              <el-table :data="roles" style="width: 100%">
                <el-table-column prop="name" label="角色" width="150" />
                <el-table-column label="权限">
                  <template #default="scope">
                    <el-checkbox-group v-model="scope.row.permissions">
                      <el-checkbox 
                        v-for="permission in allPermissions" 
                        :key="permission.value"
                        :label="permission.value"
                      >
                        {{ permission.label }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            
            <div class="step-actions">
              <el-button @click="prevStep">上一步</el-button>
              <el-button type="primary" @click="nextStep">下一步</el-button>
            </div>
          </el-card>
        </div>

        <!-- 步骤4: 完成配置 -->
        <div v-else-if="currentStep === 3" class="step-panel">
          <el-card class="step-card">
            <template #header>
              <div class="card-header">
                <el-icon><Check /></el-icon>
                <span>完成配置</span>
              </div>
            </template>
            
            <div class="completion-content">
              <el-result
                icon="success"
                title="组织设置完成"
                sub-title="您已成功完成组织的初始设置"
              >
                <template #extra>
                  <el-button type="primary" @click="goToDashboard">
                    进入仪表板
                  </el-button>
                  <el-button @click="goToOrganizationManagement">
                    组织管理
                  </el-button>
                </template>
              </el-result>
              
              <div class="summary">
                <h3>设置摘要</h3>
                <el-descriptions :column="1" border>
                  <el-descriptions-item label="组织名称">
                    {{ createdOrganization?.name }}
                  </el-descriptions-item>
                  <el-descriptions-item label="组织编码">
                    {{ createdOrganization?.code }}
                  </el-descriptions-item>
                  <el-descriptions-item label="成员数量">
                    {{ addedUsers.length }} 人
                  </el-descriptions-item>
                  <el-descriptions-item label="设置角色">
                    {{ roles.length }} 个
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  OfficeBuilding, User, Lock, Check,
  CopyDocument
} from '@element-plus/icons-vue'

// 路由
const router = useRouter()

// 响应式数据
const currentStep = ref(0)
const creatingOrganization = ref(false)
const addingUser = ref(false)
const inviteLink = ref('')

// 表单引用
const organizationFormRef = ref()
const userFormRef = ref()

// 组织表单数据
const organizationForm = reactive({
  name: '',
  code: '',
  address: '',
  contactInfo: '',
  description: ''
})

// 用户表单数据
const userForm = reactive({
  name: '',
  email: '',
  role: ''
})

// 已创建的组织
const createdOrganization = ref(null)

// 已添加的用户
const addedUsers = ref([])

// 角色和权限
const roles = ref([
  {
    name: '管理员',
    permissions: ['all']
  },
  {
    name: '普通用户',
    permissions: ['view_data', 'edit_own_data']
  },
  {
    name: '财务',
    permissions: ['view_financial', 'edit_financial']
  },
  {
    name: '采购',
    permissions: ['view_procurement', 'edit_procurement']
  }
])

const allPermissions = ref([
  { label: '查看所有数据', value: 'view_data' },
  { label: '编辑所有数据', value: 'edit_data' },
  { label: '财务管理', value: 'view_financial' },
  { label: '采购管理', value: 'view_procurement' },
  { label: '销售管理', value: 'view_sales' },
  { label: '库存管理', value: 'view_inventory' },
  { label: '系统设置', value: 'system_settings' },
  { label: '用户管理', value: 'user_management' }
])

// 表单验证规则
const organizationRules = {
  name: [
    { required: true, message: '请输入组织名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入组织编码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

const userRules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 方法
const createOrganization = async () => {
  if (!organizationFormRef.value) return
  
  await organizationFormRef.value.validate(async (valid) => {
    if (valid) {
      creatingOrganization.value = true
      try {
        // 模拟创建组织
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 保存创建的组织信息
        createdOrganization.value = {
          id: 1,
          ...organizationForm
        }
        
        ElMessage.success('组织创建成功')
        nextStep()
      } catch (error) {
        console.error('创建组织失败:', error)
        ElMessage.error('创建组织失败: ' + error.message)
      } finally {
        creatingOrganization.value = false
      }
    }
  })
}

const addUser = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      addingUser.value = true
      try {
        // 模拟添加用户
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 添加到已添加用户列表
        addedUsers.value.push({
          id: addedUsers.value.length + 1,
          ...userForm
        })
        
        // 重置表单
        Object.assign(userForm, {
          name: '',
          email: '',
          role: ''
        })
        
        ElMessage.success('用户添加成功')
      } catch (error) {
        console.error('添加用户失败:', error)
        ElMessage.error('添加用户失败: ' + error.message)
      } finally {
        addingUser.value = false
      }
    }
  })
}

const generateInviteLink = () => {
  // 生成模拟邀请链接
  inviteLink.value = `https://lingxi-system.com/invite/${Math.random().toString(36).substring(2, 15)}`
  ElMessage.success('邀请链接已生成')
}

const copyInviteLink = () => {
  navigator.clipboard.writeText(inviteLink.value)
    .then(() => {
      ElMessage.success('链接已复制到剪贴板')
    })
    .catch(() => {
      ElMessage.error('复制失败')
    })
}

const nextStep = () => {
  if (currentStep.value < 3) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const skipOnboarding = () => {
  ElMessageBox.confirm(
    '确定要跳过向导吗？您可以稍后在系统管理中完成组织设置。',
    '跳过确认',
    {
      confirmButtonText: '确定跳过',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    router.push('/dashboard')
  }).catch(() => {
    // 取消操作
  })
}

const goToDashboard = () => {
  router.push('/dashboard')
}

const goToOrganizationManagement = () => {
  router.push('/system/organizations')
}

// 生命周期
onMounted(() => {
  // 可以在这里初始化数据
})
</script>

<style scoped>
.organization-onboarding {
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  overflow: auto;
}

.onboarding-container {
  max-width: 800px;
  margin: 0 auto;
  background: white;
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.onboarding-header {
  padding: 30px;
  text-align: center;
  background: linear-gradient(135deg, #409eff 0%, #5e72e4 100%);
  color: white;
}

.onboarding-header h1 {
  margin: 0 0 10px 0;
  font-size: 28px;
  font-weight: 600;
}

.onboarding-header p {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

.step-content {
  padding: 30px;
}

.step-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
  font-weight: 500;
}

.step-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.invite-card {
  margin-bottom: 20px;
}

.invite-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.invite-header h3 {
  margin: 0;
}

.invite-link-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.form-actions {
  margin-top: 20px;
  text-align: right;
}

.completion-content {
  text-align: center;
}

.summary {
  margin-top: 30px;
  text-align: left;
}

.summary h3 {
  margin-bottom: 15px;
  font-size: 18px;
}

@media (max-width: 768px) {
  .organization-onboarding {
    padding: 10px;
  }
  
  .onboarding-container {
    margin: 0;
  }
  
  .onboarding-header {
    padding: 20px;
  }
  
  .onboarding-header h1 {
    font-size: 24px;
  }
  
  .step-content {
    padding: 20px;
  }
  
  .step-actions {
    flex-direction: column;
  }
  
  .step-actions .el-button {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .invite-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>